import { forwardRef, useMemo, useCallback, useImperativeHandle } from 'react';
import { Button, type MenuProps, Tooltip } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import CSVLogo from '@/assets/csv_icon.svg';
import { exportDataToCSV } from '@/utils/helpers';


type ExtendedProColumns = ProColumns & {
  allowExport?: boolean;
};

export interface ExportProps {
  disabled?: boolean;
  datas?: any[];
  columns: ExtendedProColumns[];
  onExport?: any;
  loading: boolean;
  onFetchExportData?: () => Promise<any[]>;
  tooltip?: React.ReactNode | string;
  showFeishuExport?: boolean;
  showCsvExport?: boolean;
  fetchExportApi?: () => Promise<any>;
}

export interface ExportHandler {
  exportCsv: (exportDatas: any[]) => void;
}

const Exports = forwardRef<ExportHandler, ExportProps>(
  (
    {
      datas,
      disabled,
      columns,
      onExport,
      loading = false,
      tooltip,
      showFeishuExport,
      showCsvExport,
      fetchExportApi,
    },
    ref,
  ) => {
    // const [currentKey, setCurrentKey] = React.useState<string>('csv');

    const items = useMemo<Exclude<MenuProps['items'], undefined>>(() => {
      return [
        {
          label: '导出CSV',
          key: 'csv',
          loading: loading,
          icon: (
            <div
              style={{
                borderRadius: 3,
                background: '#fff',
                width: 22,
                height: 22,
              }}
              className="flex justify-center items-center"
            >
              <img
                src={CSVLogo}
                style={{
                  width: 21.5,
                  height: 21.5,
                  visibility: 'visible',
                  objectFit: 'cover',
                }}
              />
            </div>
          ),
        },
      ]
    }, []);

    const exportCsv = useCallback(
      async (exportDatas: any[]) => {
        try {
          exportDataToCSV(exportDatas, columns);
        } catch (error) {
          console.error(error);
        }
      },
      [columns],
    );

    const handleExportCSV = async () => {
      if (!datas) {
        onExport && onExport(exportCsv);
      } else {
        exportCsv(datas);
      }
    };

    const dropdownItemClick = (e: any) => {
      // setCurrentKey(e.key);
      if (e.key === 'csv') {
        handleExportCSV();
      }
    };

    useImperativeHandle(ref, () => ({
      exportCsv,
    }));

    return (
      <>
        {items.map((item) => {
          const { label, key, icon, loading: btnLoading } = item as any;
          const tooltipContent = key === 'csv' && tooltip ? tooltip : label;
          return (
            <Tooltip title={tooltipContent} key={key}>
              <Button
                disabled={disabled || btnLoading}
                type="link"
                className="table-element-toolbar-button"
                onClick={() => dropdownItemClick({ key: key })}
              >
                {btnLoading ? (
                  <LoadingOutlined style={{ width: 22, color: '#1890FF' }} spin />
                ) : (
                  icon
                )}
              </Button>
            </Tooltip>
          );
        })}
      </>
      // <Dropdown
      //   menu={{
      //     items,
      //     onClick: dropdownItemClick,
      //   }}
      //   disabled={disabled || loading}
      //   trigger={['click']}
      //   placement="bottomRight"
      // >
      //   <Tooltip title={tooltip || t('__export_data')}>
      //     <Button
      //       disabled={disabled || loading}
      //       type="link"
      //       className="table-element-toolbar-button"
      //     >
      //       {loading ? (
      //         <LoadingOutlined style={{ width: 24, color: '#1890FF' }} spin />
      //       ) : (
      //         <DownloadOutlined style={{ width: 24 }} />
      //       )}
      //     </Button>
      //   </Tooltip>
      // </Dropdown>
    );
  },
);

export default Exports;
